/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *l1_next = l1;
        ListNode *l2_next = l2;
        ListNode *res = new ListNode(0);
        ListNode *current = res;
        int carry = 0;

        while(l1_next != NULL || l2_next != NULL || carry){

            int sum = carry;

            if(l1_next != NULL){
                sum += l1_next->val;
                l1_next = l1_next->next;
            }
            if(l2_next != NULL){
                sum += l2_next->val;
                l2_next = l2_next->next;
            }


            // 进位消除
            carry = sum / 10;
            current->next = new ListNode(sum % 10);
            current = current->next;

        }

        return res->next;
    }
};